<template>
    <tnxel-submit-form :model="model">
        <tnxel-alert>
            <span>建表SQL将追加至位于service层的单元测试配置文件中，如有需要可在</span>
            <span class="mx-1 link" @click="toBatchGenerateCode">批量生成代码</span>
            <span>时指定其它汇集文件</span>
        </tnxel-alert>
        <tnxel-alert type="warning" v-if="clazz.abstractClass && !clazz.inheritanceStrategy">
            未指定继承映射策略的抽象类，没有对应数据库表，无法生成建表SQL
        </tnxel-alert>
        <tnxel-alert type="warning"
            v-else-if="clazz.abstractClass && InheritanceStrategy.TABLE_PER_CLASS.equals(clazz.inheritanceStrategy)">
            当前类采用“{{ clazz.inheritanceStrategy.caption }}”继承映射策略，且为抽象类，没有对应数据库表，无法生成建表SQL
        </tnxel-alert>
        <tnxel-alert type="warning"
            v-else-if="InheritanceStrategy.SINGLE_TABLE.equals(superClassWithInheritanceStrategy?.inheritanceStrategy)">
            父类采用“{{ superClassWithInheritanceStrategy.inheritanceStrategy.caption }}”继承映射策略，建表SQL与父类相同
        </tnxel-alert>
        <tnxel-alert type="warning"
            v-else-if="InheritanceStrategy.SINGLE_TABLE.equals(clazz.inheritanceStrategy)">
            当前类采用“{{ clazz.inheritanceStrategy.caption }}”继承映射策略，汇集所有子类表的字段于一张表中
        </tnxel-alert>
        <el-form-item label="文件" label-width="44px" v-else>{{ model.path }}</el-form-item>
        <tnxel-alert type="error" v-if="model.error">{{ model.error }}</tnxel-alert>
        <template v-else-if="model.code">
            <CodePreview language="sql" :code="model.code"/>
            <div class="flex-v-center justify-content-end mt-3">
                <tnxel-button icon="fa-solid fa-floppy-disk" @click="save">
                    追加建表SQL代码到文件
                </tnxel-button>
                <tnxel-button icon="fa-solid fa-copy" @click="copy">
                    复制建表SQL代码到剪切板
                </tnxel-button>
            </div>
        </template>
    </tnxel-submit-form>
</template>

<script>
import tnx from '@/tnx';
import ModelingApp from '@/logic/modeling/entity/ModelingApp.js';
import EntityClass from '@/logic/modeling/entity/EntityClass.js';
import InheritanceStrategy from '@/logic/modeling/enums/InheritanceStrategy.js';
import GenerateUtil from '@/logic/modeling/util/generate.js';
import PersistUtil from '@/logic/modeling/util/persist.js';

import CodePreview from './components/CodePreview.vue';

export default {
    components: {
        CodePreview,
    },
    props: {
        app: {
            type: ModelingApp,
            required: true,
        },
        clazz: {
            type: EntityClass,
            required: true,
        },
    },
    data() {
        return {
            model: {
                path: null,
                code: null,
                error: null,
                warning: null,
            }
        };
    },
    computed: {
        InheritanceStrategy() {
            return InheritanceStrategy;
        },
        project() {
            return tnx.app.global.modelingProject;
        },
        superClassWithInheritanceStrategy() {
            return this.app.getSuperClassWithInheritanceStrategy(this.clazz);
        },
    },
    mounted() {
        this.refresh();
    },
    methods: {
        refresh() {
            if (!this.model.path) {
                PersistUtil.loadRelativeMavenProject(this.app.path).then(mavenProject => {
                    let root = tnx.util.file.getParentDir(this.app.path);
                    this.model.path = GenerateUtil.getPath(root, mavenProject, this.clazz, 'sql');
                });
            }
            if (!this.model.code) {
                this.model.code = GenerateUtil.generateSqlCode(this.project, this.app, this.clazz,
                    this.superClassWithInheritanceStrategy);
            }
        },
        save() {
            tnx.util.file.read(this.model.path, false, '').then(sql => {
                let firstLine = this.model.code.split('\n')[0];
                let index = sql.indexOf(firstLine);
                if (index >= 0) { // sql文件内容中已包含生成的sql的首行，则替换建表sql
                    let index2 = sql.indexOf(');\n', index);
                    sql = sql.substring(0, index) + this.model.code + sql.substring(index2 + 3);
                } else { // 否则追加建表sql
                    sql = sql.trim();
                    let key = 'set foreign_key_checks = ';
                    if (!sql.startsWith(key + '0;')) {
                        sql = key + '0;\n\n' + sql;
                    }
                    if (!sql.endsWith(key + '1;')) {
                        sql = sql.trim() + '\n\n' + key + '1;\n';
                    }
                    let index2 = sql.lastIndexOf(key + '1;');
                    sql = sql.substring(0, index2) + this.model.code + '\n' + sql.substring(index2);
                }
                sql = sql.trim() + '\n';
                GenerateUtil.save(this.model.path, sql);
            });
        },
        copy() {
            let code = this.model.code;
            if (code) {
                tnx.util.clipboard.write(code).then(() => {
                    tnx.toast('已复制');
                });
            }
        },
        toBatchGenerateCode() {
            tnx.closeDialog(false, () => {
                tnx.app.global.toolbar.toBatchGenerateCode();
            });
        },
    }
}
</script>

<style lang="scss" scoped>
</style>
